package com.study.easyexcel.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtil {

    public static InputStream getFileInputStream(String fileName){
        InputStream in = null;
        File f = new File(fileName);
        if(f.exists()){
            try {
                in = new FileInputStream(f);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }else{
            in = getResourcesFileInputStream(fileName);
        }
        return in;
    }

    public static OutputStream getFileOutPutStream(String fileName){
        try {
            File f = new File(fileName);
            if(!f.exists()){
                f.getParentFile().mkdirs();
            }
            return new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static InputStream getResourcesFileInputStream(String fileName) {
        return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    }

    public static String getPath() {
        return FileUtil.class.getResource("/").getPath();
    }

    public static String getUserDir(){
        return System.getProperty("user.dir");
    }


    public static void main(String[] args) {
        System.out.println(getPath());
    }



    public static File createNewFile(String pathName) {
        File file = new File(getPath() + pathName);
        if (file.exists()) {
            file.delete();
        } else {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
        }
        return file;
    }

    public static File readFile(String pathName) {
        return new File(getPath() + pathName);
    }

    public static File readUserHomeFile(String pathName) {
        return new File(System.getProperty("user.home") + File.separator + pathName);
    }

}
